<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--文件目录-->
      <el-col :span="4" :xs="24">
        <div class="head-container">
          <el-input
            v-model="fileName"
            placeholder="请输入文件夹名称"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="folderOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--用户数据-->
      <el-col :span="20" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5" style="padding-top:5px" >
            <el-button
              type="primary"
              icon="el-icon-upload"
              size="mini"
              @click="handleUpload"
              v-hasPermi="['store:picture:add']"
            >上传文件</el-button>
          </el-col>
          <el-col :span="1.5" style="padding-top:5px">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
              v-hasPermi="['store:picture:add']"
            >新建文件夹</el-button>
          </el-col>
<!--          <el-col :span="1.5" style="padding-top:5px">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleTest"
            >图片选择器测试</el-button>
          </el-col>-->
          <el-col :span="17" style="text-align: right">
            <el-button-group style="display: inline-block;margin-top: 5px;margin-right: 2%">
              <el-button  size="mini" @click="getByType()" >全部</el-button>
              <el-button  size="mini" @click="getByType(1)">图片</el-button>
              <el-button  size="mini" @click="getByType(2)">视频</el-button>
            </el-button-group>
              <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" style="display: inline-block;vertical-align: middle" label-width="68px" >
                <el-form-item label="" prop="fileName" style="margin-bottom: 0" >
                  <el-input
                    v-model="queryParams.fileName"
                    placeholder="请输入素材名称"
                    clearable
                    size="small"
                    @keyup.enter.native="handleQuery"
                  />
                </el-form-item>
                <el-form-item style="margin-bottom: 0" >
                  <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                  <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                </el-form-item>
              </el-form>
          </el-col>
        </el-row>
        <el-row style="margin-top: 20px;margin-bottom: 10px">
          <el-breadcrumb separator-class="el-icon-arrow-right" >
            <el-breadcrumb-item style="cursor: pointer" v-for="(item,index) in ancestorOptions" :key="index"  > {{ item.fileName }}</el-breadcrumb-item>
          </el-breadcrumb>
        </el-row>
        <el-row>
          <el-col class="picture"  v-for="(item,index) in pictureList" :key="index" :style="checkedFiles.indexOf(item.id)>-1?'border-color: #1890FF':''"  >
            <div v-if="checkedFiles.indexOf(item.id)>-1" style="position: absolute;right: -17px;top: -7px;width: 46px;height: 26px;background: #1890FF;text-align: center;transform: rotate(45deg);box-shadow: 0 1px 1px #ccc;z-index: 9" >
              <i class="el-icon-check" style="font-size: 12px;color:white;margin-top: 12px;transform: rotate(-45deg);"></i>
            </div>
            <el-image  v-if="item.type == 0" :src="folderSrc" style="height: 150px;width: 150px"  @click="handleCheckedFileChange(item.id)" @dblclick="getChildren(item.id)" ></el-image>
            <el-image  v-if="item.type == 1" :src="baseUrl+item.previewPath" style="height: 150px;width: 150px" @click="handleCheckedFileChange(item.id)" > </el-image>
            <video  v-if="item.type == 2"  :autoplay="false" controls  :src="baseUrl+item.filePath" style="height: 150px;width: 150px" @click="handleCheckedFileChange(item.id)"></video>
            <div style="margin-top: 5px">
              <input v-if="item.id == form.id" v-model="form.fileName" v-focus  @blur="updateFileNameSubmit" ></input>
              <span v-else style="display:inline-block;width:80%;padding-left:4%;padding-top:2px;overflow: hidden;white-space: nowrap;text-overflow: ellipsis;font-size: 14px;color: #606266">{{ item.fileName + item.suffix }}</span>
              <span style="display:inline-block;width:18%;float: right;padding-top: 3px" @click="updateFileName(item)"><i class="el-icon-edit"></i></span>
            </div>
          </el-col>
        </el-row>
        <el-row v-show="total>0">
          <el-col :span="1.5" style="padding-top:20px;margin-right: 15px">
            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange" >全选</el-checkbox>
          </el-col>
          <el-col :span="1.5" style="padding-top:10px;margin-right: 10px">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleMove"
              v-hasPermi="['store:picture:edit']"
            >批量移动</el-button>
          </el-col>
          <el-col :span="1.5" style="padding-top:10px">
            <el-button
              type="primary"
              plain
              size="mini"
              @click="handleDelete"
              v-hasPermi="['store:picture:remove']"
            >批量删除</el-button>
          </el-col>
          <el-col :span="19" style="text-align: right">
            <pagination
              style="padding: 0!important;margin: 0!important;"
              :total="total"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </el-col>
    </el-row>
    <!-- 新建文件夹 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="上级目录" prop="parentId">
          <treeselect v-model="form.parentId" :options="folderOptions" :show-count="true" placeholder="请选择上级目录" />
        </el-form-item>
        <el-form-item label="文件夹名称" prop="fileName">
          <el-input v-model="form.fileName" ref="fileName" placeholder="请输入文件名称" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 文件上传 -->
    <el-dialog :title="title" :visible.sync="upload" width="800px" append-to-body>
      <el-form ref="uploadForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="文件目录" prop="parentId">
          <treeselect v-model="form.parentId" :options="folderOptions" :show-count="true" placeholder="请选择上传目录" />
        </el-form-item>
        <el-form-item label="选择文件" prop="filePath">
          <picture-upload ref="pictureUpload" @input="getChildEvent"  ></picture-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="submitUploadForm">
          <span v-if="!loading">确 定</span>
          <span v-else>上 传 中...</span>
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 移动文件 -->
    <el-dialog :title="title" :visible.sync="move" width="400px" append-to-body>
      <el-form ref="moveForm" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="文件目录" prop="parentId">
          <treeselect v-model="form.parentId" :options="folderOptions" :show-count="true" placeholder="请选择目标目录" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary"  @click="movePicture">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 图片选择器测试 -->
<!--    <el-dialog title="图片空间" class="myDialog" :visible.sync="test" width="1030px" style="padding: 0" append-to-body>
      <picture-selector ></picture-selector>
      <div slot="footer" class="dialog-footer">
        <el-button type="text" style="float: left"  @click="submitTest">进入图片空间</el-button>
        <span style="font-size: 12px;margin-right: 20px ">已选3个</span>
        <el-button type="primary"  @click="submitTest">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>-->
  </div>
</template>

<script>
import {
  listFile,
  getFile,
  delFile,
  addFile,
  updateFile,
  treeSelect,
  uploadFiles, moveFile
} from "@/api/picture/file";
import Treeselect from "@riophae/vue-treeselect";
import PictureUpload from "@/components/PictureUpload"
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import folderSrc from "../../../assets/images/folder.png";
import PictureSelector from "@/views/picture/file/selector";

export default {
  name: "File",
  components: {
    Treeselect,
    PictureUpload,
    PictureSelector
  },
  data() {
    return {
      test:false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      folderSrc:folderSrc,
      baseUrl: process.env.VUE_APP_BASE_API,
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 总条数
      total: 0,
      // 图片管理表格数据
      pictureList: [],
      //将要上传得文件
      fileList:[],
      // 弹出层标题
      title: "",
      // 文件夹选项
      folderOptions: undefined,
      //祖籍
      ancestorOptions:[{id:0,fileName:"全部文件"}],
      // 创建文件夹弹出层
      open: false,
      //文件上传弹出层
      upload:false,
      //移动文件弹出层
      move:false,
      // 文件夹名称
      fileName: undefined,
      //全选
      checkAll: false,
      checkedFiles: [],
      fileType:["png", "jpg", "jpeg","mp4"],
      isIndeterminate: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        parentId: 0,
        fileName: null,
        type:null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        parentId: [
          { required: true, message: "上级目录不能为空", trigger: ["blur","change" ]}
        ],
        fileName: [
          { required: true, message: "文件名称不能为空", trigger: "blur" }
        ],
        filePath: [
          { required: true, message: "文件不能为空", trigger:["blur","change" ] }
        ]
      }
    };
  },
  watch: {
    // 根据名称筛选文件夹树
    fileName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    this.getTreeSelect();
    this.getList();
  },
  methods: {
    handleTest(){
      this.test=true;
    },
    submitTest(){
      this.test=false;
    },
    /** 查询图片管理列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.pictureList = response.rows;
        this.ancestorOptions = response.data;
        this.total = response.total;
        this.checkedFiles =[];
        this.checkAll = false;
        this.isIndeterminate = false;
        this.loading = false;
      });
    },
    /** 查询文件目录树结构 */
    getTreeSelect() {
      treeSelect().then(response => {
        this.folderOptions = response.data;
      });
    },
    getChildren(id){
      this.queryParams.parentId=id;
      this.queryParams.type=undefined;
      this.getList();
    },
    getByType(type){
      this.queryParams.type=type;
      this.getList();
    },
    getFolderName(id){
      if(id == 0){
        return "全部文件"
      }
      this.folderOptions.forEach(function (val,index) {
        if(val.id == id){
          return val.label
        }
      })
      return ''
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.parentId = data.id;
      this.queryParams.type=undefined;
      this.getList();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.upload=false;
      this.move=false
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        extAppId: null,
        parentId: 0,
        ancestors: null,
        fileName: null,
        filePath:null,
        type: null,
        suffix: null,
        width: null,
        height: null,
        size: null,
        ids:[]
      };
      this.resetForm("form");
      this.resetForm("uploadForm");
      //this.fileList=[];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新建文件夹按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "新建文件夹";
      if(this.queryParams.parentId){
        this.form.parentId = this.queryParams.parentId
      }
      this.$nextTick(() => {
        this.$refs.fileName.focus()
      })
    },
    handleUpload() {
      this.reset();
      this.upload = true;
      this.title = "文件上传";
      this.form.type = 1;
      if(this.queryParams.parentId){
        this.form.parentId = this.queryParams.parentId
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getFile(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改文件夹";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateFile(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getTreeSelect();
            });
          } else {
            addFile(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getTreeSelect();
              this.getList();
            });
          }
        }
      });
    },
    getChildEvent(fileList){
      this.fileList=fileList;
      this.$refs.uploadForm.clearValidate("filePath")
    },
    handleBeforeUpload(file) {

        // 校检文件大小
        if (fileExtension == 'mp4') {
          const isLt = file.size / 1024 / 1024 < 50;
          if (!isLt) {
            this.$message.error(`视频文件文件大小不能超过50MB!`);
            return false;
          } else {
            const isLt = file.size / 1024 / 1024 < 1;
            if (!isLt) {
              this.$message.error(`单个文件文件大小不能超过2MB!`);
              return false;
            }
          }
        }
      return true;
    },
    submitUploadForm(){
      let imgForm = new FormData()
      let isOk =true;
      this.fileList.forEach(file =>{
        //文件类型校验
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        if (this.fileType.indexOf(fileExtension) < 0) {
          isOk= false;
          this.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
          return false
        }
        //文件大小验证
        // 校检文件大小
        if (fileExtension == 'mp4') {
          const isLt = file.size / 1024 / 1024 < 50;
          if (!isLt) {
            isOk= false;
            this.$message.error(`单个视频大小不能超过50MB!`);
            return false;
          }
        }
        else {
          const isLt = file.size / 1024 / 1024 < 2;
          if (!isLt) {
            isOk= false;
            this.$message.error(`单个图片大小不能超过2MB!`);
            return false;
          }
        }
        imgForm.append("files",file.raw);
        this.form.filePath="abc"
      });
      if(!isOk){
        return
      }
      imgForm.append("parentId",this.form.parentId);
      imgForm.append("type",this.form.type);
      this.loading = true;
      this.$refs["uploadForm"].validate(valid => {
        if (valid) {
          uploadFiles(imgForm).then(response => {
            this.msgSuccess("上传成功");
            this.upload = false;
            this.$refs.pictureUpload.reset();
            this.getList();
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete() {
      if(this.checkedFiles==0){
        this.msgInfo("您还没有选择要删除的文件");
        return
      }
      const ids = this.checkedFiles;
      this.$confirm('是否确认删除选中的文件吗?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delFile(ids);
        }).then(() => {
          this.getTreeSelect()
          this.getList();
          this.checkedFiles=[];
          this.checkAll = false;
          this.isIndeterminate = false;
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    updateFileName(item){
      this.form=item;
    },
    updateFileNameSubmit(){
      if(this.form.fileName){
        updateFile(this.form).then(response => {
          if(this.form.type == 0){
            this.getTreeSelect();
          }
          this.reset()
          this.getList();
        });
      }else {
        this.reset()
        this.getList()
        this.msgError("文件名不能为空！")
      }
    },
    handleCheckAllChange(val) {
      if(val){
        let that=this;
        this.pictureList.forEach(function (value){
          that.checkedFiles.push(value.id)
        })
      }else {
        this.checkedFiles = []
      }
      this.isIndeterminate = false;
    },
    handleCheckedFileChange(id) {
      //判断有没有
      const findex = this.checkedFiles.indexOf(id);
      if(findex>-1){
        this.checkedFiles.splice(findex, 1);
      }else {
        this.checkedFiles.push(id)
      }
      let checkedCount = this.checkedFiles.length;
      this.checkAll = checkedCount === this.pictureList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.pictureList.length;
    },
    /** 新建文件夹按钮操作 */
    handleMove() {
      this.reset();
      this.move = true;
      this.title = "移动文件";
      if(this.queryParams.parentId){
        this.form.parentId = this.queryParams.parentId
      }
    },
    movePicture(){
      if(this.checkedFiles==0){
        this.msgInfo("您还没有选择要移动的文件")
        return
      }
      //判断选中的文件夹包含目标文件
      if(this.checkedFiles.indexOf(this.form.parentId) > -1){
        this.msgError("不允许移动到已被选中的文件夹！")
        return
      }
      const ids = this.checkedFiles;
      this.$refs["moveForm"].validate(valid => {
        if (valid) {
          this.form.ids = ids;
          moveFile(this.form).then(response => {
            this.getTreeSelect();
            this.getList();
            this.checkedFiles=[];
            this.checkAll = false;
            this.isIndeterminate = false;
            this.move=false;
            this.msgSuccess("移动成功！");
          })
        }
      })
    }
  }
};
</script>

<style lang="scss" scoped>
  .picture {
    width: 152px;
    height: 190px;
    margin-right:10px;
    margin-bottom:10px;
    border: 1px solid #DCDFE6;
    position: relative;
    overflow: hidden
  }
  .picture input{
    font-size: 14px;
    margin-left: 5px;
    width:75% ;
    margin-top: -5px;
    height: 30px ;
    line-height: 30px
  }
</style>
<style lang="scss">
  .myDialog .el-dialog__body{
    padding: 0 10px!important;
  }
</style>
